'use strict';
const db = uniCloud.database();
const dbForJQL = uniCloud.databaseForJQL();
const businessDBName = 'zhy_business_info';
const userDBName = 'zhy_user_info';
const userConsumeDBName = 'zhy_consume_record';
const allowenceDBName = 'zhy_allowence_record';
const consumeQueueDBName = 'zhy_comsume_queue';
const dbCmd = db.command
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ', event)
	if (event.queryType == 1) {
		// 查询参与人数 参与活动数
		return getActivityNum(event, context)
	} else if (event.queryType == 2) {
		// 查询用户消费记录
		return queryUserConsumeRecord(event, context)
	} else if (event.queryType == 3) {
		// 查询用户消费记录：提现信息
		return queryUserConsumeByTixian(event, context)
	}
	//返回数据给客户端
	// return event
	console.log('参数非法');
	return ''
};

async function queryUserConsumeRecord(params, context) {
	let result = [];
	if (objIsEmpty(params)) {
		return {
			errSubject: 'param_lack',
			errCode: 0,
			errMsg: '参数不齐',
			data: []
		}
	}
	/* const consumeRecordList = dbForJQL.collection(userConsumeDBName).where({
		user_id: params.user_id,
		consume_status: 1
	}).orderBy('consume_time', 'desc').skip(params.skip).limit(params.size).getTemp();
	console.log(JSON.stringify(consumeRecordList));
	const resultRes = await dbForJQL.collection(consumeRecordList, businessDBName).field(
		'user_id,business_id as businessInfo,consume_amount,consume_status,consume_time,consume_order').get(); */
	let resultRes = await db.collection(userConsumeDBName).where({
		user_id: params.user_id
	}).orderBy('consume_time', 'desc').skip(params.skip).limit(params.size).get({
		getCount: true
	})
	let resultList = resultRes.data
	// 判断商家是否可排队:设置 join_platform_guarantee_plan和 business_store_name
	await getBusinessJoinJihuaStatus(resultList)
	// 获取用户排队数量:设置 consume_queue_num
	await getUserComsumePaiweiNum(resultList)
	return resultList;
}


async function getActivityNum(params, context) {
	let result = {
		joinActivityNum: 0,
		businessJoinActivityNum: 0
	};
	if (objIsEmpty(params)) {
		return {
			errSubject: 'param_lack',
			errCode: 0,
			errMsg: '参数不齐',
			data: result
		}
	}
	// 不需要去重
	let joinActivityNum = await db.collection(userConsumeDBName).where({
		user_id: params.userId,
		consume_status: 1
	}).count()
	result.joinActivityNum = joinActivityNum.total
	if (!objIsEmpty(params.businessId)) {
		// if (params.businessId != undefined && params.businessId != null && params.businessId != '') {
		let businessJoinActivityNum = await db.collection(userConsumeDBName).where({
			business_id: params.businessId,
			consume_status: 1
		}).field({
			user_id: true
		}).count()
		result.businessJoinActivityNum = businessJoinActivityNum.total
		console.log(businessJoinActivityNum.total);
	}
	return result;
}

async function queryUserConsumeByTixian(event, context) {
	let list = []
	if (objIsEmpty(event)) {
		return list
	}
	const consumeRecordList = dbForJQL.collection(userConsumeDBName).where({
		user_id: event.user_id,
		// consume_status: 1
	}).orderBy('consume_time', 'desc').skip(event.skip).limit(event.size).getTemp();
	console.log(JSON.stringify(consumeRecordList));
	const resultRes = await dbForJQL.collection(consumeRecordList, businessDBName).field(
			'user_id,business_id as businessInfo,consume_amount,consume_status,consume_time,max_allowence_amount')
		.get();
	list = resultRes.data
	if (list == null || list.length == 0) {
		return list
	}
	// 获取该用户在这些商户下的补贴记录:进度，可提现余额等
	return await getUserAllowenceAndProgress(list, event.user_id);
}
//====================================非业务函数======================================//
function objIsEmpty(obj) {
	if (obj == null || obj == '' || obj == undefined || JSON.stringify(obj) == '{}') {
		return true
	}
	return false
}

// 获取该用户在这些商户下的补贴记录:
// 增加字段：progress进度，withdrawableBalance可提取额度,分，allowencedAmount已补贴金额,分
// 返回list:{business_id,user_id,allowencedAmount,max_allowence_amount,progress,withdrawableBalance(单位:分)}
async function getUserAllowenceAndProgress(consumeList, userId) {
	for (let i = 0; i < consumeList.length; i++) {
		// 需要计算
		let item = consumeList[i]
		let allowenced = await db.collection(allowenceDBName).where({
			consume_id: item._id
		}).get()
		if (allowenced == null || allowenced.data.length == 0) {
			// 无补贴记录
			item.allowencedAmount = 0
		} else {
			let allowencedAmount = 0
			let allowencedList = allowenced.data
			for (let j = 0; j < allowencedList.length; j++) {
				let jtem = allowencedList[j]
				allowencedAmount = allowencedAmount + jtem.zhb_allowence_amount
			}
			item.allowencedAmount = allowencedAmount
		}
		if (item.consume_status == 2 || item.consume_status == 3) {
			// 已完成/已退出
			item.withdrawableBalance = 0
		} else {
			item.withdrawableBalance = item.allowencedAmount
		}
		// Math.round(num*10000)/100 四舍五入，保留两位小数
		let progress = Math.round((item.allowencedAmount / item.max_allowence_amount) * 10000) / 100
		item.progress = progress
	}
	return consumeList
}

// 获取加入平台保障计划状态:设置 join_platform_guarantee_plan和 business_store_name
async function getBusinessJoinJihuaStatus(consumeList) {
	if (objIsEmpty(consumeList)) {
		return consumeList
	}
	for (let i = 0; i < consumeList.length; i++) {
		let consumeItem = consumeList[i]
		if (!objIsEmpty(consumeItem.business_id)) {
			let bs = await getBusinessInfo(consumeItem.business_id)
			if (objIsEmpty(bs)) {
				consumeItem.join_platform_guarantee_plan = 0
			} else {
				consumeItem.business_store_name = bs.store_name
				if (objIsEmpty(bs.join_platform_guarantee_plan)) {
					consumeItem.join_platform_guarantee_plan = 0
				} else if (bs.join_platform_guarantee_plan == 1) {
					consumeItem.join_platform_guarantee_plan = 1
				} else {
					consumeItem.join_platform_guarantee_plan = 0
				}
			}
		} else {
			// 没有则 未加入
			consumeItem.join_platform_guarantee_plan = 0
		}
	}
}

async function getBusinessInfo(business_id) {
	if (objIsEmpty(business_id)) {
		return null
	}
	let res = await db.collection(businessDBName).where({
		offlineBusinessId: business_id
	}).limit(1).get()
	if (res == null || res == undefined || res.data == null || res.data.length == 0) {
		return null
	}
	return res.data[0]
}

// 获取用户排队数量:设置 consume_queue_num
async function getUserComsumePaiweiNum(consumeList) {
	if (objIsEmpty(consumeList)) {
		return consumeList
	}
	for (let i = 0; i < consumeList.length; i++) {
		let consumeItem = consumeList[i]
		if (consumeItem.consume_status == 1) {
			let userBSQueue = await getUserConsumeQueue(consumeItem.user_id, consumeItem.business_id)
			/* let countResult = await db.collection(consumeQueueDBName).where({
				// consume_id: consumeItem._id,
				business_id: consumeItem.business_id,
				isDelete: 0,
				consume_order: dbCmd.lte(consumeItem.consume_order)
			}).count()
			console.log(JSON.stringify(countResult)); */
			// {"affectedDocs":0,"total":0}
			// consumeItem.consume_queue_num = countResult.total
			if (userBSQueue == null) {
				consumeItem.consume_queue_num = 0
			} else {
				// 顺序按照order依次递增的！
				consumeItem.consume_queue_num = userBSQueue.consume_order
			}
		} else {
			// 已退出/已完成均为0
			consumeItem.consume_queue_num = 0
		}

	}
}

async function getUserConsumeQueue(user_id, business_id) {
	let res = await db.collection(consumeQueueDBName).where({
		user_id: user_id,
		business_id: business_id,
		isDelete: 0,
	}).limit(1).get()
	if (res == null || res.data == null || res.data.length == 0) {
		return null
	}
	return res.data[0]
}